package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.SMSUtils;
import com.itheima.reggie.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired(required = false)
    private UserService userService;

    @Autowired(required = false)
    private RedisTemplate redisTemplate;

    @RequestMapping("/login")
    public R<User> login(@RequestBody Map<String,String> map,HttpSession session) {
        String phone = map.get("phone");
        String userCode = map.get("code");
      //  String sessionCode = (String) session.getAttribute(phone);
        String sessionCode = (String) redisTemplate.opsForValue().get(phone);

        User loginUser = userService.login(phone, userCode, sessionCode);

        if(loginUser != null){
            session.setAttribute("user", loginUser.getId());
          //  session.removeAttribute(phone);
            redisTemplate.delete(phone);
            return R.success(loginUser);
        }
        return R.error("登录失败");
    }

    @PostMapping("/sendMsg")
     public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        System.out.println(user);
        //   1.生成一个4位随机数字验证码
        String phone = user.getPhone();
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        //  打印验证码
        System.out.println("验证码：" + code);
        // 2.发送短信
        // SMSUtils.sendMessage("黑马旅游网", "SMS_198917972", "14737676370", code);
      //  session.setAttribute(user.getPhone(),code);
        redisTemplate.opsForValue().set(phone, code, 1, TimeUnit.MINUTES);
        return R.success("发送验证码短信成功");
    }
}

